package com.example.car.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.car.R
import com.example.car.bean.BrandListBean
import com.example.car.databinding.ItemBrandlistBinding

class BrandListAdapter(var ctx: Context, var mDatas: MutableList<BrandListBean.ResultBean>) :
    RecyclerView.Adapter<BrandListAdapter.BrandHolder>() {

    val inflater = LayoutInflater.from(ctx)

    // item子布局项
    class BrandHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var binding: ItemBrandlistBinding? = null
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BrandHolder {
        // 将item子项绑定到RecyclerView上
        val binding: ItemBrandlistBinding = DataBindingUtil.inflate(
            inflater, R.layout.item_brandlist, parent, false
        )
        val holder = BrandHolder(binding.root)
        // 保存子布局根对象
        holder.binding = binding
        return holder
    }

    override fun onBindViewHolder(holder: BrandHolder, position: Int) {
        val bean = mDatas.get(position)
        // 将数据对象赋值给子布局中的变量item
        // 从而减少在代码层面进行代码的编写
        holder.binding?.item = bean
    }

    override fun getItemCount(): Int {
        return mDatas.size
    }

    fun addDatas(list: List<BrandListBean.ResultBean>?) {
        if (list != null) {
            mDatas.addAll(list)
            notifyDataSetChanged()
        }
    }
}
